# -*- coding: utf-8 -*-
import threading

from PyQt5.QtWidgets import QMainWindow
import qtawesome as qta

from global_data.glabal_data import GlobalData
from mq.zmq.zmq_tools import Server
from utils.time_utils import TimeUtils
from windows.zmq_pub import Ui_win_zmq_pub


class ZmqPubForm(object):
    def __init__(self, id, parent):
        self.id = id
        self.parent = parent
        self.sender = None
        self.ui = Ui_win_zmq_pub()
        self.win = QMainWindow()
        self.win.setWindowIcon(qta.icon(GlobalData.SYS_ICON))
        self.init()
        self.bind_events()

    def init(self):
        self.ui.setupUi(self.win)
        self.ui.txt_ip.setText(GlobalData.ZMQ_XSUB_IP)
        self.ui.txt_port.setText(GlobalData.ZMQ_XSUB_PORT)
        self.ui.txt_topic.setText("alarm")
        self.ui.txt_content.setPlainText("测试消息推送。。。。。")

    def bind_events(self):
        self.ui.btn_start_pub.clicked.connect(self.start)
        self.ui.btn_stop_pub.clicked.connect(self.stop)
        self.ui.btn_send.clicked.connect(self.send_msg)

    def create_server(self):
        self.sender = Server(host=self.ui.txt_ip.text(), port=self.ui.txt_port.text())

    def start(self):
        if self.sender:
            self.ui.tb_log.append(f"发布线程已存在，请不要重复启动。。。。。")
            return
        self.ui.tb_log.append(f"启动发布线程。。。。。")
        # sender_thread = threading.Thread(target=self.create_server)
        # sender_thread.setDaemon(True)  # 守护线程  主线程退出后，自动退出
        # sender_thread.start()
        self.create_server()

    def stop(self):
        try:
            if self.sender:
                self.sender.close()
                self.sender = None
                self.ui.tb_log.append(f"停止发布。。。。。")
            else:
                self.ui.tb_log.append(f"发布不存在。。。。。")
        except Exception as e:
            self.ui.tb_log.append(f"停止服务失败: {e}")

    def send_msg(self):
        if self.sender:
            self.sender.send_multi_str(self.ui.txt_topic.text(), self.ui.txt_content.toPlainText())
            self.ui.tb_log.append(f"发送消息：time={TimeUtils.get_current_time()}, topic={self.ui.txt_topic.text()}, message={self.ui.txt_content.toPlainText()}")
        else:
            self.ui.tb_log.append(f"发布不存在。。。。。")


if __name__ == '__main__':
    print("Python")
